package com.sugar.subscribe.course.module.business.dal.redis.objlock;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import static com.sugar.subscribe.course.module.business.dal.redis.RedisKeyConstants.BUSINESS_OBJECT_LOCK;

/**
 * @author Ysugar
 */
@Slf4j
@Repository
public class ObjectLockRedisDAO {


    @Resource
    private RedissonClient redissonClient;

    public void lock(Long id, Long timeoutMillis, Runnable runnable) {
        String lockKey = formatKey(id);
        RLock lock = redissonClient.getLock(lockKey);
        try {
            lock.lock(timeoutMillis, TimeUnit.MILLISECONDS);
            // 执行逻辑
            runnable.run();
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
    }

    public <R> R lockGet(Long id, Long timeoutMillis, Supplier<R> supplier) {
        String lockKey = formatKey(id);
        RLock lock = redissonClient.getLock(lockKey);
        try {
            lock.lock(timeoutMillis, TimeUnit.MILLISECONDS);
            // 执行逻辑
            return supplier.get();
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
    }

    private static String formatKey(Long id) {
        return String.format(BUSINESS_OBJECT_LOCK, id);
    }
}
